<template>
  <BasicModal v-bind="$attrs" width="300" destroyOnClose :title="title"
    :canFullscreen="false" :maskClosable="false" :showCancelBtn="false" :showOkBtn="false" :centered="true"
    @register="registerModal" @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" :model="modelRef"/>
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from '../banner.data';
import { saveOrUpdate } from '../banner.api';
import { select } from "/@/views/weixin/menu/menu.api";

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
//设置标题
const title    = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
const modelRef = ref({});
//表单配置
const [registerForm, { resetFields, setFieldsValue, updateSchema, validate, clearValidate }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
});

//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await resetFields();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  modelRef.value = {};

  if (isUpdate.value) {
    Object.assign(modelRef, data.record);
  }
  console.info("@@@@", modelRef)
  updateSchema([
    {
      field: "linkMode",
      componentProps: { 
        onChange: (value) => {
          if (value == '1') {
            modelRef.value = { linkUrl: '', goodsName: '' }
          }
          clearValidate();
        },
      },
    },
    {
      field: "categoryId",
      componentProps: { 
        api: select,
        onSelect: (value, node, extra) => {
          modelRef.value = { linkUrl: node.id + "," + node.fatherid, goodsName: node.name }
          console.info(modelRef.value)
          clearValidate();
        },
      },
    },
  ])

  // 无论新增还是编辑，都可以设置表单值
  // console.info("data.record@@", data.record.cId)
  if (typeof data.record === "object") {
    await setFieldsValue({
      ...data.record
    });
  }

  clearValidate();
});

//表单提交事件
async function handleSubmit() {
  try {
    let values = await validate();

    console.info(values);
    console.info(modelRef.value);

    setModalProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success', { isUpdate: isUpdate.value, values });
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>

<style lang="less" scoped>
</style>